package com.AdvancedDemos.FileAndIO;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.function.Function;
import java.util.stream.Collectors;

public class 练习3 {
    public static void main(String[] args) throws IOException {
        /**
         * 用户注册,在模块下的userMessage.txt文件中,存在如下的用户信息
         *     张三,123456
         *     李四,123456
         *     王五,123456
         * 程序运行,提示用户输入要注册的用户名,如果该用户名已经存在,则提示:
         * 用户名重复,请重新输入
         * 否则,提示用户名可用,提示输入密码,并将该新用户信息追加存储在
         *     userMessage.txt文件中
         */

        //1.读取文件中用户的信息
        ArrayList<String> list = new ArrayList<>();//用于存储每个用户信息
        BufferedReader br = new BufferedReader(new FileReader("helloworld\\src\\com\\AdvancedDemos\\FileAndIO\\userMessage.txt"));
        String line;
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        br.close();

        //2.将String信息封装成User1类对象
        List<User1> users = list.stream().map(new Function<String, User1>() {
            @Override
            public User1 apply(String s) {
                return new User1(s.split(",")[0], s.split(",")[1]);
            }
        }).collect(Collectors.toList())
        /*.forEach(new Consumer<User1>() {
            @Override
            public void accept(User1 user1) {
                System.out.println(user1);
//                User1{name='张三', pwd='123456'}
//                User1{name='李四', pwd='123456'}
//                User1{name='王五', pwd='123456'}
            }
        })*/;
        System.out.println(users);//[User1{name='张三', pwd='123456'}, User1{name='李四', pwd='123456'}, User1{name='王五', pwd='123456'}]

        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String name = sc.nextLine();
        Iterator<User1> iterator = users.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getName().equals(name)) {
                throw new IllegalArgumentException("用户名重复");
            }
        }
        System.out.println("请输入密码");
        String pwd = sc.nextLine();

        //将新的信息追加写入原始文件
        BufferedWriter bw = new BufferedWriter(new FileWriter("helloworld\\src\\com\\AdvancedDemos\\FileAndIO\\userMessage.txt", true));
        bw.write(name + "," + pwd);
        bw.newLine();
        bw.close();

    }
}

class User1 {
    private String name;
    private String pwd;

    public User1() {
    }

    public User1(String name, String pwd) {
        this.name = name;
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User1{" + "name='" + name + '\'' + ", pwd='" + pwd + '\'' + '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
}
